package dyy.zc.sportruler.ui.fragment;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.datatype.BmobFile;
import dyy.zc.sportruler.R;
import dyy.zc.sportruler.application.MyApplication;
import dyy.zc.sportruler.base.BaseFragment;
import dyy.zc.sportruler.bean.PlanInfo;
import dyy.zc.sportruler.bean.SportName;
import dyy.zc.sportruler.bean.StudentInfo;
import dyy.zc.sportruler.listener.OnItemClickListener;
import dyy.zc.sportruler.permission.PermissionsChecker;
import dyy.zc.sportruler.ui.activity.MakePlanActivity;
import dyy.zc.sportruler.ui.adapter.LabelAdapter;
import dyy.zc.sportruler.utils.AproriUtils;
import dyy.zc.sportruler.utils.BmobUtils;
import dyy.zc.sportruler.utils.DataInfo;
import dyy.zc.sportruler.utils.ImageUploadUtil;
import dyy.zc.sportruler.utils.ImageUtil;
import dyy.zc.sportruler.utils.LogUtils;
import dyy.zc.sportruler.utils.MakePlanUtils;
import dyy.zc.sportruler.utils.ToastUtils;
import dyy.zc.sportruler.utils.Utils;
import dyy.zc.sportruler.views.ActionSheet;

/**
 * Created by chuan on 2017/5/6.
 */

public class MakePlanFragment extends BaseFragment implements View.OnClickListener, ActionSheet.OnSheetItemClickListener {
    private TextView title,next;
//    private TextView add;
    private ImageView head;
    private boolean hasHead = false;
    private EditText et_name,et_phone,et_other;
    private TextView man,woman,tv_age;
    private boolean manOrWoman = true;
    private LinearLayout ll_height,ll_weight,ll_jirou,ll_tizhi,ll_age;
    private List<String> dataList = new ArrayList<>();
    private int select = 0;
    private TextView height,weight,jirou,tizhi;
    private RecyclerView recyclerView,partRecyclerView;
    private LabelAdapter adapter;
    private LabelAdapter partAdapter;
    private List<String> wantLabelList = new ArrayList<>();
    private List<String> wantPartList = new ArrayList<>();
    private View view;
    private BmobUtils bmobUtils;
    private String[] items = {"拍照", "我的相册"};
    // 头像文件、上传头像的名称、本地图片uri
    private File imageFile;
    private Uri imageUri; // 图片路径
    public ImageView civ_head;
    private String saveFileName = "";
    private PermissionsChecker mPermissionsChecker; // 权限检测器
    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
    };
    public static int type = 0;
    //拍照、从相册选择、照片保存成功
    private final int TAKE_PHOTO = 1, CHOOSE_PHOTO = 2,SAVE_IMAGE_SUCCESS = 3 ,SAVE_IMAGE_FAILED = 4;
    private final int REQUEST_CODE = 0;

    private StudentInfo studentInfo;
    private TextView bmi,daixie,jiroulv;

    private MyBroadCastReceiver receiver;
    private void findViewsByIds(View view) {

        receiver = new MyBroadCastReceiver();
        IntentFilter filter = new IntentFilter("data");
        getActivity().registerReceiver(receiver,filter);

        title = Utils.findViewsById(view,R.id.top_tv_title);
        next = Utils.findViewsById(view,R.id.top_tv_right);
//        add = Utils.findViewsById(view,R.id.add);
        head = Utils.findViewsById(view,R.id.head);
        bmi = Utils.findViewsById(view,R.id.bmi);
        daixie = Utils.findViewsById(view,R.id.daixie);
        jiroulv = Utils.findViewsById(view,R.id.jiroulv);
        et_name = Utils.findViewsById(view,R.id.et_name);
        et_phone = Utils.findViewsById(view,R.id.et_phone);
        et_other = Utils.findViewsById(view,R.id.et_other);
        man = Utils.findViewsById(view,R.id.tv_man);
        woman = Utils.findViewsById(view,R.id.tv_woman);
        ll_height = Utils.findViewsById(view,R.id.ll_height);
        ll_weight = Utils.findViewsById(view,R.id.ll_weight);
        ll_jirou = Utils.findViewsById(view,R.id.ll_jirou);
        ll_tizhi = Utils.findViewsById(view,R.id.ll_tizhi);
        ll_age = Utils.findViewsById(view,R.id.ll_age);
        height = Utils.findViewsById(view,R.id.tv_height);
        weight = Utils.findViewsById(view,R.id.tv_weight);
        jirou = Utils.findViewsById(view,R.id.tv_jirou);
        tizhi = Utils.findViewsById(view,R.id.tv_tizhi);
        tv_age = Utils.findViewsById(view,R.id.tv_age);
        recyclerView = Utils.findViewsById(view,R.id.recyclerView);
        partRecyclerView = Utils.findViewsById(view,R.id.part_recyclerView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(receiver);
    }

    @Override
    protected View onCreateViews(LayoutInflater inflater, ViewGroup container) {
        view = inflater.inflate(R.layout.fragment_make_plan,container,false);
        findViewsByIds(view);
        setData();
        initData();
        bind();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        MakePlanUtils.isFirst = true;//修改选择动作界面为第一次执行
        MakePlanUtils.sp_relaxAction.clear();
        MakePlanUtils.sp_warmUp.clear();
        MakePlanUtils.sp_mainAction.clear();
        MakePlanUtils.sp_stretching.clear();
    }

    private void setData() {
        wantLabelList.add("塑型");
        wantLabelList.add("增肌");
        wantLabelList.add("减脂");
        wantPartList.add("胸部");
        wantPartList.add("背部");
        wantPartList.add("腿部");
        wantPartList.add("肩部");
        wantPartList.add("腹部");
        for (int i = 0;i<220;i++){
            dataList.add(i+"");
        }
    }

    private void initData() {
        title.setText("学员资料");
        next.setText("下一步");
        df = new DecimalFormat("#0.00");
        studentInfo = new StudentInfo();
        next.setVisibility(View.VISIBLE);
        next.setTextColor(getResources().getColor(R.color.text_blue));
        bmobUtils = new BmobUtils(getActivity());
        studentInfo = new StudentInfo();
        Utils.findViewsById(view,R.id.top_rl_back).setVisibility(View.GONE);

        adapter = new LabelAdapter(getActivity(), wantLabelList);
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
        recyclerView.setAdapter(adapter);

        partAdapter = new LabelAdapter(getActivity(),wantPartList);
        partRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
        partRecyclerView.setAdapter(partAdapter);
        caculater();
        getData();

    }

    private void bind() {
        ll_height.setOnClickListener(setDataListener);
        ll_weight.setOnClickListener(setDataListener);
        ll_jirou.setOnClickListener(setDataListener);
        ll_tizhi.setOnClickListener(setDataListener);
        ll_age.setOnClickListener(setDataListener);
//        add.setOnClickListener(this);
        head.setOnClickListener(this);

        man.setOnClickListener(sexListener);
        woman.setOnClickListener(sexListener);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                int pre = adapter.p;
                adapter.p = position;
                if (pre != -1){
                    adapter.notifyItemChanged(pre);
                }
                adapter.notifyItemChanged(position);
            }
        });

        partAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                int pre = partAdapter.p;
                partAdapter.p = position;
                if (pre != -1){
                    partAdapter.notifyItemChanged(pre);
                }
                partAdapter.notifyItemChanged(position);
            }
        });
    }

    /**
     * 设置数据
     */
    private View.OnClickListener setDataListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.ll_height:select = 0;break;
                case R.id.ll_weight:select = 1;break;
                case R.id.ll_jirou:select = 2;break;
                case R.id.ll_tizhi:select = 3;break;
                case R.id.ll_age:select = 4;break;
            }
            initPopUpWindow(dataList, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switch (select){
                        case 0://身高
                            height.setText(""+dataList.get(datePicker.getCurrentItemPosition())+"cm");
                            heightStr = dataList.get(datePicker.getCurrentItemPosition());
                            break;
                        case 1://体重
                            weight.setText(""+dataList.get(datePicker.getCurrentItemPosition())+"kg");
                            weightStr = dataList.get(datePicker.getCurrentItemPosition());
                            break;
                        case 2://肌肉
                            jirou.setText(""+dataList.get(datePicker.getCurrentItemPosition())+"kg");
                            jirouStr = dataList.get(datePicker.getCurrentItemPosition());
                            break;
                        case 3://体脂
                            tizhi.setText(""+dataList.get(datePicker.getCurrentItemPosition())+"%");
                            break;
                        case 4://年龄
                            tv_age.setText(""+dataList.get(datePicker.getCurrentItemPosition())+"岁");
                            ageStr = dataList.get(datePicker.getCurrentItemPosition());
                            break;
                    }
                    caculater();
                    mPopupWindow.dismiss();
                }
            });
        }
    };

    private DecimalFormat df;
    private String ageStr = "24";
    private String heightStr = "178";
    private String weightStr = "70";
    private String jirouStr = "20";
    private String BMIStr = "";
    private String jiroulvStr = "";
    private String daixieStr = "";
    private void caculater(){
        //BMI
//        男性基础代谢率（kcal/day）=66＋（13.7×体重kg）＋（5×身高cm）－（6.8×年龄）
//        ·女性基础代谢率（kcal/day）=65＋（9.6×体重kg）＋（1.8×身高cm）－（4.7×年龄）
        double Dweight = Double.valueOf(weightStr);
        double Dheight = Double.valueOf(heightStr);
        double Djirou = Double.valueOf(jirouStr);
        double Dage = Double.valueOf(ageStr);
        double BMI = Dweight/((Dheight/100)*(Dheight/100));
//        Log.e("BMI",BMI+"");
        bmi.setText("BMI:"+df.format(BMI)+"");
        double da = 0;
        jiroulv.setText("肌肉率:"+df.format(Djirou/Dweight*100)+"%");
        if (manOrWoman){
             da = 66+(13.7*Dweight)+(5*Dheight)-(6.8*Dage);
            daixie.setText("基础代谢:"+df.format(da)+"(kcal/day)");
        }else {
             da = 65+(9.6*Dweight)+(1.8*Dheight)-(4.7*Dage);
            daixie.setText("基础代谢:"+df.format(da)+"(kcal/day)");
        }
        BMIStr = df.format(BMI);
        jiroulvStr = df.format(Djirou/Dweight*100);
        daixieStr = df.format(da);
    }

    /**
     * 性别设置
     */
    private View.OnClickListener sexListener = new View.OnClickListener() {
        @Override
        public void onClick(View v){
            if (manOrWoman){//true 男 false 女
                manOrWoman = false;
                man.setBackgroundResource(R.drawable.shape_conrner_normal);
                woman.setBackgroundResource(R.drawable.shape_conrner);
                caculater();
            }else {
                manOrWoman = true;
                man.setBackgroundResource(R.drawable.shape_conrner);
                woman.setBackgroundResource(R.drawable.shape_conrner_normal);
                caculater();
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top_rl_right:
                if (hasHead&&!et_name.getText().toString().equals("")){
                    studentInfo.setName(et_name.getText().toString());
                    studentInfo.setPhone(et_phone.getText().toString());
                    studentInfo.setSex(manOrWoman);
                    studentInfo.setAge(tv_age.getText().toString());
                    studentInfo.setHeight(height.getText().toString());
                    studentInfo.setWeight(weight.getText().toString());
                    studentInfo.setJirou(jirou.getText().toString());
                    studentInfo.setTizhi(tizhi.getText().toString());
                    studentInfo.setWanted(wantLabelList.get(adapter.p));
                    studentInfo.setPart(wantPartList.get(partAdapter.p));
                    studentInfo.setOther(et_other.getText().toString());
                    studentInfo.setTeacherID(loginuser.getId());
                    studentInfo.setBmi(BMIStr);
                    studentInfo.setJiroulv(jiroulvStr);
                    studentInfo.setDaixie(daixieStr);
//                    analyticalData();
                    Intent intent = new Intent(getActivity(), MakePlanActivity.class);
                    intent.putExtra("student",studentInfo);
                    startActivity(intent);
                }else {
                    ToastUtils.shortToast(getActivity(),"请输入完整信息");
                }

                break;
            case R.id.head:
                showActionSheetDialog(items);
                break;
        }
    }

    /**
     * 获取关联数据
     */

    public void getData(){
        LogUtils.e("开始获取关联数据");
        bmobUtils.getAllPlanInfo(333,404,handler);
        bmobUtils.getAllStudentInfo(444,505,handler);
    }


    /**
     * 头像选择对话框
     */
    private void showActionSheetDialog(String[] items) {
        ActionSheet actionSheet = new ActionSheet(getActivity())
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (int i = 0; i < items.length; i++) {
            actionSheet.addSheetItem(items[i], ActionSheet.SheetItemColor.Blue, MakePlanFragment.this);
        }
        actionSheet.show();

    }

    @Override
    public void onClick(int which) {
        switch (which) {
            case TAKE_PHOTO:
                //拍照
                imageFile = ImageUploadUtil.createImageFile(ImageUploadUtil.CAMERA_SAVEDIR2, ImageUploadUtil.createImageName());
                startActivityForResult(ImageUploadUtil.intentImageCapture(imageFile), ImageUploadUtil.TAKE_PHOTO);
                break;
            case CHOOSE_PHOTO:
                //从相册选择
                startActivityForResult(ImageUtil.intentChooseImg(),
                        CHOOSE_PHOTO);
                break;
        }
    }


    /**
     * Activity回调事件处理
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == 0) {
                    return;
                }
                //拍照
                ImageUtil.paizhaocreateImagefile(getActivity(), imageFile);
                if (imageFile == null) {
                    ToastUtils.shortToast(getActivity(), "图片太大无法上传");
                    return;
                }
                doSendThread();//上传图片
                break;
            case CHOOSE_PHOTO:
                //相册
                if (resultCode == 0) return;
                imageUri = data.getData();
                imageFile = MyApplication.getInstance().createimagefile(imageUri, getVmWidth(), getVmHeight());
                if (imageFile == null) {
                    ToastUtils.shortToast(getActivity(), "imageFile为空2");
                    return;
                }
                doSendThread();//上传图片
                break;
        }
    }

    /**
     * 上传头像
     */
    private void doSendThread() {
        dialog = ProgressDialog.show(getActivity(),null,"正在上传头像");
        BmobFile bmobFile = new BmobFile(imageFile);
        bmobUtils.upLoadFile(bmobFile,SAVE_IMAGE_SUCCESS,SAVE_IMAGE_FAILED,handler);

    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case SAVE_IMAGE_SUCCESS:
                    dialog.dismiss();
                    Bundle bundle = msg.getData();
                    BmobFile bmobFile = (BmobFile) bundle.getSerializable("file");
                    if (bmobFile != null){
                        studentInfo.setHead(bmobFile);
                        hasHead = true;
                        Glide.with(getActivity()).load(bmobFile.getFileUrl())
                                .error(R.drawable.chat_xe_icon2_03).into(head);
                    }
                    break;
                case SAVE_IMAGE_FAILED:
                    dialog.dismiss();
                    ToastUtils.shortToast(getActivity(),"网络故障，请稍后重试");
                    break;
                case 333:
                    Bundle bundle1 = msg.getData();
                    List<PlanInfo> planInfo = (List<PlanInfo>) bundle1.getSerializable("list");
                    if (planInfo!=null){
                        DataInfo.planInfoList.clear();
                        DataInfo.planInfoList.addAll(planInfo);
                    }
                    getActivity().sendBroadcast(new Intent("data"));
//                    AproriUtils.setRecord(listAll);
//                    AproriUtils.start();
                    break;
                case 444:
                    Bundle bundle2 = msg.getData();
                    List<StudentInfo> s = (List<StudentInfo>) bundle2.getSerializable("list");
                    if (s!=null){
                        DataInfo.studentInfoList.clear();
                        DataInfo.studentInfoList.addAll(s);
                    }
                    getActivity().sendBroadcast(new Intent("data"));
                    break;
                case 404://若是获取失败，重新获取
                    bmobUtils.getAllPlanInfo(333,404,handler);
//                    ToastUtils.shortToast(getActivity(),"网络故障，请稍后重试");
                    break;
                case 505://若是获取失败，重新获取
                    bmobUtils.getAllStudentInfo(444,505,handler);
                    break;
                case 999:
                    Utils.findViewsById(view,R.id.top_rl_right).setOnClickListener(MakePlanFragment.this);
                    break;
            }
        }
    };
    private int getDataCount = 0;
    private class MyBroadCastReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("data")){
                getDataCount++;
                if (getDataCount==2){
                    handler.sendEmptyMessage(999);
                }
            }
        }
    }
}
